<?php

namespace iBrand\Shop\Server\Controllers\V2;

use iBrand\Common\Controllers\Controller;
use iBrand\Component\Balance\Model\Balance;
use iBrand\Component\Point\Repository\PointRepository;
use iBrand\Shop\Core\Models\User;
use iBrand\Shop\Core\Repositories\UserShopRepository;
use iBrand\Component\Discount\Repositories\CouponRepository;
use iBrand\Shop\Server\Resources\ShopUser;
use Illuminate\Http\Request;
use Validator;
use DB;

class UserController extends Controller
{
    protected $userShopRepository;
    protected $couponRepository;
    protected $pointRepository;

    public function __construct(UserShopRepository $userShopRepository, CouponRepository $couponRepository, PointRepository $pointRepository)
    {
        $this->userShopRepository = $userShopRepository;
        $this->couponRepository = $couponRepository;
        $this->pointRepository = $pointRepository;
    }

    public function store(Request $request)
    {
        $input = $request->except('file', '_token');
        $table = config('ibrand.app.database.prefix', 'ibrand_') . 'user';
        $unique = isset($input['user_id']) && $input['user_id'] ? 'unique:' . $table . ',mobile,' . $input['user_id'] : 'unique:' . $table . ',mobile';

        $rules = [
            //'nick_name' => 'required',
            'mobile' => 'required|' . $unique,
        ];
        $message = [
            "required" => ":attribute 不能为空",
            "unique" => ":attribute 已存在",
        ];

        $attributes = [
            //	'nick_name' => '姓名',
            'mobile' => '手机号',
        ];

        $validator = Validator::make($input, $rules, $message, $attributes);
        if ($validator->fails()) {

            return $this->failed($validator->messages()->first());
        }

        try {
            DB::beginTransaction();

            $clerk = auth('clerk')->user();
            if (isset($input['user_id']) && $input['user_id']) {
                $user = User::find($input['user_id']);
                $user->nick_name = $input['nick_name'];
                $user->mobile = $input['mobile'];
                $user->sex = $input['sex'];
                $user->avatar = $input['avatar'];
                $user->birthday = $input['birthday'];
                $user->save();
            } else {
                $user = User::create([
                    'nick_name' => $input['nick_name'],
                    'mobile' => $input['mobile'],
                    'password' => '123456',
                    'sex' => $input['sex'],
                    'avatar' => $input['avatar'],
                    'birthday' => $input['birthday'],
                ]);

                $this->userShopRepository->create([
                    'user_id' => $user->id,
                    'clerk_id' => $clerk->id,
                    'shop_id' => $clerk->shop_id,
                ]);

                event('user.created.gift', [$user->id]);
            }

            DB::commit();

            return $this->success();
        } catch (\Exception $exception) {
            \Log::info($exception->getTraceAsString());

            DB::rollBack();

            return $this->failed('添加失败');
        }
    }

    /**
     * 获取会员信息列表
     */
    public function getUsersByCredentials()
    {
        $clerk = auth('clerk')->user();
        $shop_id = $clerk->shop_id;
        $keyword = request('keyword');

        if (!$keyword) {
            $users = $this->userShopRepository->getUserListByShopId($shop_id);
        } else {
            $users = $this->userShopRepository->getUserListByCredentials($keyword, $shop_id);

            /* 搜索会员，如果没有则自动注册，这个功能去掉
             * if ($users->count() == 0 AND is_mobile($keyword) AND request('type')=='cash_register') {
                $user = User::create([
                    'mobile' => $keyword
                ]);
                $this->userShopRepository->create([
                    'user_id' => $user->id,
                    'clerk_id' => $clerk->id,
                    'shop_id' => $clerk->shop_id,
                ]);

                $users = $this->userShopRepository->getUserListByCredentials($keyword, $shop_id);
            }*/

        }

        return $this->paginator($users, ShopUser::class);
    }

    public function detail($user_id)
    {
        $user = User::where('id', $user_id)->where('status', 1)->first();
        if (!$user) {
            return $this->failed('用户不存在');
        }

        $user->point = $this->pointRepository->getSumPointValid($user_id, 'default');
        $user->balance = Balance::SumByUser($user_id);
        $coupons = $coupons = $this->couponRepository->findActiveByUser($user_id, false, 'shop');
        $user->coupons = $coupons->count();
        $user->user_id = $user_id;

        return $this->success($user);
    }

    public function getSystemUser()
    {
        $clerk = auth('clerk')->user();
        $shop_id = $clerk->shop_id;

        $users = $this->userShopRepository->getUserListByCredentials('13399999999', $shop_id);

        return $this->paginator($users, ShopUser::class);
    }
}